package com.bankoption.config;

import javax.servlet.ServletContext;

import com.bankoption.controller.admin.AdminController;
import com.bankoption.controller.admin.ConfigController;
import com.bankoption.controller.admin.QueryFieldController;
import com.bankoption.model._MappingKit;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.render.FreeMarkerRender;

import freemarker.template.TemplateModelException;

public class MainConfig extends JFinalConfig{

	@Override
	public void configConstant(Constants me) {
		// 加载少量必要配置，随后可用PropKit.get(...)获取值
		PropKit.use("config.properties");
		me.setDevMode(true);
	}

	@Override
	public void configRoute(Routes me) {
		me.add("/admin",AdminController.class,"/admin");
		me.add("/config",ConfigController.class,"/admin/config");
		me.add("/config/queryfield",QueryFieldController.class,"/admin/config");
	}

	@Override
	public void configPlugin(Plugins me) {
		C3p0Plugin c3p0Plugin = createC3p0Plugin();
		me.add(c3p0Plugin);
		ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		me.add(arp);
		
		// 所有数据映射配置在 MappingKit 中搞定
		_MappingKit.mapping(arp);
	}
	
	public static C3p0Plugin createC3p0Plugin() {
		return new C3p0Plugin(PropKit.get("db.url"), PropKit.get("db.username"), PropKit.get("db.password"));
	}

	@Override
	public void configInterceptor(Interceptors me) {
		
	}

	@Override
	public void configHandler(Handlers me) {
		
	}
	
	@Override
	public void afterJFinalStart() {
		//在freemarker中设置项目路径作为全局变量
		ServletContext context = JFinal.me().getServletContext();
			try {
				FreeMarkerRender.getConfiguration().setSharedVariable("ctx", context.getContextPath());
			} catch (TemplateModelException e) {
				e.printStackTrace();
			}
		super.afterJFinalStart();
	}

}
